package com.milk.nettylearn.nio.c4;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.*;
import java.util.Iterator;

@Slf4j
public class SelectorServer {
    public static void main(String[] args) throws IOException, InterruptedException {
        Selector selector = Selector.open();
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.configureBlocking(false);
        serverSocketChannel.bind(new InetSocketAddress(8080));

        SelectionKey selectionKey = serverSocketChannel.register(selector, 0, null);
        selectionKey.interestOps(SelectionKey.OP_ACCEPT);

        while (true) {
            // 阻塞到有事件发生
            selector.select();

            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()) {
                SelectionKey next = iterator.next();
                log.debug("key {}", next);
//                ServerSocketChannel channel = (ServerSocketChannel) next.channel();
//                SocketChannel socketChannel = channel.accept();
//                log.debug("socketChannel 连接上:{}", socketChannel);\
                Thread.sleep(500);
                log.debug("key valid {}",next.isValid());
                next.cancel();
            }
        }
    }
}
